package com.zhu.service.base.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class RabbitMqConfig {
    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;

    @Bean
    public Queue registerMailQueue(){
        return new Queue(MailConstance.MAIL_QUEUE_NAME);
    }
    @Bean
    public DirectExchange mailExchange(){
        return new DirectExchange(MailConstance.MAIL_EXCHANGE);
    }
    @Bean
    public Binding registerMailBinding(){
        return BindingBuilder.bind(registerMailQueue()).to(mailExchange()).with(MailConstance.MAIL_ROUTEING_KEY_NAME);
    }

    @Bean
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate=new RabbitTemplate(cachingConnectionFactory);

        /**
         * 消息确认回调，确认消息是否到达broker
         */
        /**
         * data:消息唯一标识
         * ack：确认结果
         * cause：失败原因
         */
        rabbitTemplate.setConfirmCallback((data,ack,cause)->{
            String msgId = data.getId();
            if(ack){
                log.info("{}=======>消息发送成功",msgId);

            }else{
                log.error("{}======>消息发送失败，",msgId);
            }
        });
        /**
         * 消息失败回调，
         * msg:消息主题
         * repCode：响应码
         * repText：响应描述
         * exchange：交换机
         */
        rabbitTemplate.setReturnCallback((msg,repCode,repText,exchange,routingkey)->{
            log.error("{}=====>消息发送到quequ失败", msg.getBody());
        });
        return rabbitTemplate;
    }
}
